<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { deviceApi } from '@T2/service/api.ts';
import { saveAs } from 'file-saver';
import ExcelJS from 'exceljs';

const props = defineProps({
  unit: {
    type: Object,
    required: true,
  },
});

const getDevicesByUnit = () => {
  if (!props.unit.id) {
    ElMessage.error('未选中站点！')
    return null;
  }
  return new Promise((resolve, reject) => {
    deviceApi({
      method: 'get',
      params: {
        unit: props.unit.id,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      reject(err);
    })
  })
}
const handleExport = async () => {
  const lists = await getDevicesByUnit();
  if (!lists?.length) {
    ElMessage.error('未查询到设备！')
    return;
  }
  exportToExcel(lists)
}

const exportToExcel = async (lists) => {
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('Sheet1');
  
  const headerKeys = {
    code: '设备位号',
    name: '设备名称',
    addr: '安装位置',
    use_time: '投运日期',
    cycle: '维保周期',
    product_name: '产品名称',
    product_gg: '规格型号',
    brand: '品牌',
    remark: '备注',
    
    supplier_name: '厂商名称',
    supplier_people: '联系人',
    supplier_phone: '联系电话',
    supplier_addr: '地址',
    supplier_info: '说明',
  };
  /* 定义列 */
  const columns = [];
  Object.keys(headerKeys).forEach(key => {
    columns.push({ header: headerKeys[key], key: key, width: 18 });
  });
  worksheet.columns = columns;
  
  /* 添加数据 */
  lists.forEach(item => {
    let obj = {};
    Object.keys(headerKeys).forEach(key => {
      obj[key] = item[key] === null ? '' : item[key];
    });
    worksheet.addRow(obj);
  });
  /* 更新表头样式 */
  const headerRow = worksheet.getRow(1);
  headerRow.height = 30;          // 行高设置为 30
  headerRow.font = {
    bold: true,                   // 粗体
    color: { argb: '00000000' },  // 字体颜色（白色）
    size: 12,                     // 字体大小
  };
  /* 设置居中对齐 */
  headerRow.eachCell((cell) => {
    cell.alignment = {
      vertical: 'middle',         // 垂直居中
      horizontal: 'center',       // 水平居中
    };
  });
  /* 设置背景样式 */
  for (let i = 1; i <= 9; i++) {
    headerRow.getCell(i).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFFFE699' }, // 黄色ffe699
    };
  }
  for (let i = 10; i <= 14; i++) {
    headerRow.getCell(i).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FF5B9BD5' }, // 蓝色5b9bd5
    };
  }
  /* 设置边框所有边框 */
  worksheet.eachRow({ includeEmpty: true }, (row) => {
    row.eachCell((cell) => {
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' },
      };
    });
  });
  
  // 确保行高设置生效
  // headerRow.commit();
  
  /* 导出 Excel 文件 */
  const buffer = await workbook.xlsx.writeBuffer();
  const blob = new Blob([buffer], { type: 'application/octet-stream' });
  saveAs(blob, `设备台账-${ props.unit.name }.xlsx`);
};

</script>

<template>
  <el-button @click="handleExport()">导出</el-button>
</template>

<style lang="scss" scoped>

</style>